import ddddocr
import requests
from jsonpath import jsonpath

from utils.encrypt import get_real_password


class Session:
    '''
    会话类,所有测试用例共用一个会话类对象,
    第一次获取对象时会完成登录再返回对象
    后面再获取对象时直接返回这个对象
    '''
    __session = None
    __header = None

    @classmethod
    def get_session(cls):
        '''
        该方法不用传入参数,返回同一个Session对象
        :return:
        '''
        if cls.__session is None:
            cls.__session = requests.Session()
            cls.test_gettoken()
        return cls.__session
    
    @classmethod
    def test_gettoken(cls):
        '''
        使用session完成登录
        :return:
        '''
        # 获取验证码图片的token
        url = 'http://120.53.243.26:8009/api/validateCode/getToken'

        resp = cls.__session.get(url=url)
        jdata = resp.json()

        # 提取出验证码图片的token
        token = jsonpath(jdata,"$..token")
        token = token[0]

        # 获取验证码图片
        pic_url = 'http://120.53.243.26:8009/api/validateCode/refreshCode/' + token
        resp = cls.__session.get(url=pic_url)
        with open('vcode.png',mode='wb') as f:
            f.write(resp.content)


        # 识别验证码
        ocr = ddddocr.DdddOcr()
        with open("vcode.png", 'rb') as f:
            image = f.read()
        vcode = ocr.classification(image)

        #获取密钥
        encrypt_key_url = 'http://120.53.243.26:8009/api/getTransEncryptKey'
        resp = cls.__session.get(url=encrypt_key_url)
        body = resp.json()
        key = jsonpath(body,"$..transEncryptKey")
        transToken = jsonpath(body, '$..transToken')

        # 密码加密
        encrypted_pwd = get_real_password('123456', key=key[0])

        #准备登录数据
        login_url = 'http://120.53.243.26:8009/api/login'
        data = {"continueLoginFlag": "",
                "password": encrypted_pwd,
                "token": token,
                "transToken": transToken[0],
                "userNo": "admin",
                "validateCode": vcode}

        # 发送登录请求
        resp = cls.__session.post(url=login_url,json=data)
        print('requests:')
        print(resp.request.headers)
        print(resp.request.body)


        body = resp.json()
        session_token = jsonpath(body,'$..token')

        cls.__session.close()
        session_token = 'Bearer ' + session_token[0]
        cls.__header = {'Authorization':session_token}

    @classmethod
    def get_header(cls):
        return cls.__header

if __name__ == '__main__':
    s1 = Session.get_session()
    # s = requests.Session()
    # print(Session.get_header())

    # s2 = Session.get_session()
    # s3 = Session.get_session()
    # print(id(s1))
    # print(id(s2))
    # print(id(s3))